package com.example.offer;

import com.alibaba.fastjson.JSON;

import java.util.*;

/**
 * 剑指 Offer 59 - I. 滑动窗口的最大值
 * 给定一个数组 nums 和滑动窗口的大小 k，请找出所有滑动窗口里的最大值。
 * <p>
 * 示例:
 * <p>
 * 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
 * 输出: [3,3,5,5,6,7]
 * 解释:
 * <p>
 * 滑动窗口的位置                最大值
 * ---------------               -----
 * [1  3  -1] -3  5  3  6  7       3
 * 1 [3  -1  -3] 5  3  6  7       3
 * 1  3 [-1  -3  5] 3  6  7       5
 * 1  3  -1 [-3  5  3] 6  7       5
 * 1  3  -1  -3 [5  3  6] 7       6
 */
public class MaxSlidingWindow {
    public static void main(String[] args) {
        MaxSlidingWindow solution = new MaxSlidingWindow();
        int[] nums = {5, 4, 3, 2, 1, 0};
        System.out.println(JSON.toJSONString(solution.maxSlidingWindow(nums, 3)));


    }

    public int[] maxSlidingWindow(int[] nums, int k) {
        int length = nums.length;
        if (length <= 1 || k == 1) return nums;
        Queue<Integer> queue = new PriorityQueue<>(k, Comparator.reverseOrder());
        for (int i = 0; i < k - 1; i++) {
            queue.add(nums[i]);
        }
        int pre = 0, max;
        int[] res = new int[length - k + 1];
        for (int i = k - 1; i < length; i++) {
            queue.add(nums[i]);
            max = queue.peek();
            queue.remove(nums[pre]);
            res[pre] = max;
            pre++;
        }
        return res;
    }
}

/**
 * 剑指 Offer 59 - II. 队列的最大值
 * 请定义一个队列并实现函数 max_value 得到队列里的最大值，要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
 * <p>
 * 若队列为空，pop_front 和 max_value 需要返回 -1
 * <p>
 * 示例 1：
 * <p>
 * 输入:
 * ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
 * [[],[1],[2],[],[],[]]
 * 输出: [null,null,null,2,1,2]
 */
class MaxQueue {
    Queue<Integer> queue;
    Deque<Integer> stack;

    public MaxQueue() {
        queue = new PriorityQueue<>(Comparator.reverseOrder());
        stack = new LinkedList<>();
    }

    public int max_value() {
        return queue.peek() == null ? -1 : queue.peek();
    }

    public void push_back(int value) {
        queue.add(value);
        stack.add(value);
    }

    public int pop_front() {
        if (stack.size() == 0) return -1;
        int a = stack.removeFirst();
        queue.remove(a);
        return a;
    }
}